package com.bjbn.service;

import com.bjbn.entity.BridgeInfo;
import com.bjbn.entity.BridgeInfoHistory;
import com.bjbn.entity.BridgePowerInfoHistory;
import com.bjbn.entity.BridgeAirConditioningInfoHistory;
import com.bjbn.mapper.BridgeInfoMapper;
import com.bjbn.mapper.BridgeInfoHistoryMapper;
import com.bjbn.mapper.BridgePowerInfoHistoryMapper;
import com.bjbn.mapper.BridgeAirConditioningInfoHistoryMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 数据迁移服务
 */
@Slf4j
@Service
public class DataMigrationService {

    private static final int BATCH_SIZE = 1000; // 每次从MySQL读取的记录数

    @Autowired
    private BridgeInfoService bridgeInfoService;

    @Autowired
    private BridgeInfoHistoryService bridgeInfoHistoryService;

    @Autowired
    private BridgePowerInfoHistoryService bridgePowerInfoHistoryService;

    @Autowired
    private BridgeAirConditioningInfoHistoryService bridgeAirConditioningInfoHistoryService;

    @Autowired
    private BridgeInfoMapper bridgeInfoMapper;

    @Autowired
    private BridgeInfoHistoryMapper bridgeInfoHistoryMapper;

    @Autowired
    private BridgePowerInfoHistoryMapper bridgePowerInfoHistoryMapper;

    @Autowired
    private BridgeAirConditioningInfoHistoryMapper bridgeAirConditioningInfoHistoryMapper;

    /**
     * 开始廊桥信息数据迁移
     */
    @Async("migrationTaskExecutor")
    public CompletableFuture<String> startMigration() {
        try {
            log.info("开始廊桥信息数据迁移...");
            if (!bridgeInfoService.createIndex("bridge_info")) {
                return CompletableFuture.completedFuture("创建ES索引失败");
            }
            if (!bridgeInfoService.deleteAll()) {
                return CompletableFuture.completedFuture("清空ES数据失败");
            }
            Long totalCount = bridgeInfoMapper.countTotal();
            if (totalCount == null || totalCount == 0) {
                return CompletableFuture.completedFuture("MySQL中没有数据需要迁移");
            }
            log.info("MySQL中共有{}条记录需要迁移", totalCount);
            int totalBatches = (int) Math.ceil((double) totalCount / BATCH_SIZE);
            int processedCount = 0;
            for (int batchNum = 0; batchNum < totalBatches; batchNum++) {
                int offset = batchNum * BATCH_SIZE;
                List<BridgeInfo> batchData = bridgeInfoMapper.selectPage(offset, BATCH_SIZE);
                if (batchData.isEmpty()) {
                    break;
                }
                if (bridgeInfoService.saveBridgeInfoBatch(batchData)) {
                    processedCount += batchData.size();
                    log.info("批次 {}/{} 数据迁移完成，处理了{}条记录", batchNum + 1, totalBatches, batchData.size());
                } else {
                    log.error("批次 {}/{} 数据迁移失败", batchNum + 1, totalBatches);
                    return CompletableFuture.completedFuture("批次 " + (batchNum + 1) + " 数据迁移失败");
                }
            }
            long esCount = bridgeInfoService.count();
            if (esCount == totalCount) {
                log.info("廊桥信息数据迁移完成！MySQL: {}条，ES: {}条", totalCount, esCount);
                return CompletableFuture.completedFuture("廊桥信息数据迁移完成！共迁移" + totalCount + "条记录");
            } else {
                log.error("廊桥信息数据迁移验证失败！MySQL: {}条，ES: {}条", totalCount, esCount);
                return CompletableFuture.completedFuture("廊桥信息数据迁移验证失败！MySQL: " + totalCount + "条，ES: " + esCount + "条");
            }
        } catch (Exception e) {
            log.error("廊桥信息数据迁移过程中发生异常", e);
            return CompletableFuture.completedFuture("廊桥信息数据迁移异常: " + e.getMessage());
        }
    }

    /**
     * 开始廊桥信息历史数据迁移
     */
    @Async("migrationTaskExecutor")
    public CompletableFuture<String> startHistoryMigration() {
        try {
            log.info("开始廊桥信息历史数据迁移...");
            if (!bridgeInfoHistoryService.createIndex("bridge_info_history")) {
                return CompletableFuture.completedFuture("创建ES历史索引失败");
            }
            if (!bridgeInfoHistoryService.deleteAll()) {
                return CompletableFuture.completedFuture("清空ES历史数据失败");
            }
            Long totalCount = bridgeInfoHistoryMapper.countTotal();
            if (totalCount == null || totalCount == 0) {
                return CompletableFuture.completedFuture("MySQL中没有历史数据需要迁移");
            }
            log.info("MySQL中共有{}条历史记录需要迁移", totalCount);
            int totalBatches = (int) Math.ceil((double) totalCount / BATCH_SIZE);
            int processedCount = 0;
            for (int batchNum = 0; batchNum < totalBatches; batchNum++) {
                int offset = batchNum * BATCH_SIZE;
                List<BridgeInfoHistory> batchData = bridgeInfoHistoryMapper.selectPage(offset, BATCH_SIZE);
                if (batchData.isEmpty()) {
                    break;
                }
                if (bridgeInfoHistoryService.saveBridgeInfoHistoryBatch(batchData)) {
                    processedCount += batchData.size();
                    log.info("批次 {}/{} 历史数据迁移完成，处理了{}条记录", batchNum + 1, totalBatches, batchData.size());
                } else {
                    log.error("批次 {}/{} 历史数据迁移失败", batchNum + 1, totalBatches);
                    return CompletableFuture.completedFuture("批次 " + (batchNum + 1) + " 历史数据迁移失败");
                }
            }
            long esCount = bridgeInfoHistoryService.count();
            if (esCount == totalCount) {
                log.info("廊桥信息历史数据迁移完成！MySQL: {}条，ES: {}条", totalCount, esCount);
                return CompletableFuture.completedFuture("廊桥信息历史数据迁移完成！共迁移" + totalCount + "条记录");
            } else {
                log.error("廊桥信息历史数据迁移验证失败！MySQL: {}条，ES: {}条", totalCount, esCount);
                return CompletableFuture.completedFuture("廊桥信息历史数据迁移验证失败！MySQL: " + totalCount + "条，ES: " + esCount + "条");
            }
        } catch (Exception e) {
            log.error("廊桥信息历史数据迁移过程中发生异常", e);
            return CompletableFuture.completedFuture("廊桥信息历史数据迁移异常: " + e.getMessage());
        }
    }

    /**
     * 开始廊桥电源信息历史数据迁移
     */
    @Async("migrationTaskExecutor")
    public CompletableFuture<String> startPowerInfoHistoryMigration() {
        try {
            log.info("开始廊桥电源信息历史数据迁移...");
            if (!bridgePowerInfoHistoryService.createIndex("bridge_power_info_history")) {
                return CompletableFuture.completedFuture("创建ES电源信息历史索引失败");
            }
            if (!bridgePowerInfoHistoryService.deleteAll()) {
                return CompletableFuture.completedFuture("清空ES电源信息历史数据失败");
            }
            Long totalCount = bridgePowerInfoHistoryMapper.countTotal();
            if (totalCount == null || totalCount == 0) {
                return CompletableFuture.completedFuture("MySQL中没有电源信息历史数据需要迁移");
            }
            log.info("MySQL中共有{}条电源信息历史记录需要迁移", totalCount);
            int totalBatches = (int) Math.ceil((double) totalCount / BATCH_SIZE);
            int processedCount = 0;
            for (int batchNum = 0; batchNum < totalBatches; batchNum++) {
                int offset = batchNum * BATCH_SIZE;
                List<BridgePowerInfoHistory> batchData = bridgePowerInfoHistoryMapper.selectPage(offset, BATCH_SIZE);
                if (batchData.isEmpty()) {
                    break;
                }
                if (bridgePowerInfoHistoryService.saveBridgePowerInfoHistoryBatch(batchData)) {
                    processedCount += batchData.size();
                    log.info("批次 {}/{} 电源信息历史数据迁移完成，处理了{}条记录", batchNum + 1, totalBatches, batchData.size());
                } else {
                    log.error("批次 {}/{} 电源信息历史数据迁移失败", batchNum + 1, totalBatches);
                    return CompletableFuture.completedFuture("批次 " + (batchNum + 1) + " 电源信息历史数据迁移失败");
                }
            }
            long esCount = bridgePowerInfoHistoryService.count();
            if (esCount == totalCount) {
                log.info("廊桥电源信息历史数据迁移完成！MySQL: {}条，ES: {}条", totalCount, esCount);
                return CompletableFuture.completedFuture("廊桥电源信息历史数据迁移完成！共迁移" + totalCount + "条记录");
            } else {
                log.error("廊桥电源信息历史数据迁移验证失败！MySQL: {}条，ES: {}条", totalCount, esCount);
                return CompletableFuture.completedFuture("廊桥电源信息历史数据迁移验证失败！MySQL: " + totalCount + "条，ES: " + esCount + "条");
            }
        } catch (Exception e) {
            log.error("廊桥电源信息历史数据迁移过程中发生异常", e);
            return CompletableFuture.completedFuture("廊桥电源信息历史数据迁移异常: " + e.getMessage());
        }
    }

    /**
     * 获取迁移状态
     */
    public String getMigrationStatus() {
        try {
            long mysqlCount = bridgeInfoMapper.countTotal();
            long esCount = bridgeInfoService.count();
            return String.format("MySQL: %d条，ES: %d条", mysqlCount, esCount);
        } catch (Exception e) {
            log.error("获取迁移状态失败", e);
            return "获取迁移状态失败: " + e.getMessage();
        }
    }

    /**
     * 获取历史数据迁移状态
     */
    public String getHistoryMigrationStatus() {
        try {
            long mysqlCount = bridgeInfoHistoryMapper.countTotal();
            long esCount = bridgeInfoHistoryService.count();
            return String.format("MySQL历史数据: %d条，ES历史数据: %d条", mysqlCount, esCount);
        } catch (Exception e) {
            log.error("获取历史数据迁移状态失败", e);
            return "获取历史数据迁移状态失败: " + e.getMessage();
        }
    }

    /**
     * 获取电源信息历史数据迁移状态
     */
    public String getPowerInfoHistoryMigrationStatus() {
        try {
            long mysqlCount = bridgePowerInfoHistoryMapper.countTotal();
            long esCount = bridgePowerInfoHistoryService.count();
            return String.format("MySQL电源信息历史数据: %d条，ES电源信息历史数据: %d条", mysqlCount, esCount);
        } catch (Exception e) {
            log.error("获取电源信息历史数据迁移状态失败", e);
            return "获取电源信息历史数据迁移状态失败: " + e.getMessage();
        }
    }

    /**
     * 开始廊桥飞机空调信息历史数据迁移
     */
    @Async("migrationTaskExecutor")
    public CompletableFuture<String> startAirConditioningInfoHistoryMigration() {
        try {
            log.info("开始廊桥飞机空调信息历史数据迁移...");
            if (!bridgeAirConditioningInfoHistoryService.createIndex("bridge_air_conditioning_info_history")) {
                return CompletableFuture.completedFuture("创建ES飞机空调信息历史索引失败");
            }
            if (!bridgeAirConditioningInfoHistoryService.deleteAll()) {
                return CompletableFuture.completedFuture("清空ES飞机空调信息历史数据失败");
            }
            Long totalCount = bridgeAirConditioningInfoHistoryMapper.countTotal();
            if (totalCount == null || totalCount == 0) {
                return CompletableFuture.completedFuture("MySQL中没有飞机空调信息历史数据需要迁移");
            }
            log.info("MySQL中共有{}条飞机空调信息历史记录需要迁移", totalCount);
            int totalBatches = (int) Math.ceil((double) totalCount / BATCH_SIZE);
            int processedCount = 0;
            for (int batchNum = 0; batchNum < totalBatches; batchNum++) {
                int offset = batchNum * BATCH_SIZE;
                List<BridgeAirConditioningInfoHistory> batchData = bridgeAirConditioningInfoHistoryMapper.selectPage(offset, BATCH_SIZE);
                if (batchData.isEmpty()) {
                    break;
                }
                if (bridgeAirConditioningInfoHistoryService.saveBridgeAirConditioningInfoHistoryBatch(batchData)) {
                    processedCount += batchData.size();
                    log.info("批次 {}/{} 飞机空调信息历史数据迁移完成，处理了{}条记录", batchNum + 1, totalBatches, batchData.size());
                } else {
                    log.error("批次 {}/{} 飞机空调信息历史数据迁移失败", batchNum + 1, totalBatches);
                    return CompletableFuture.completedFuture("批次 " + (batchNum + 1) + " 飞机空调信息历史数据迁移失败");
                }
            }
            long esCount = bridgeAirConditioningInfoHistoryService.count();
            if (esCount == totalCount) {
                log.info("廊桥飞机空调信息历史数据迁移完成！MySQL: {}条，ES: {}条", totalCount, esCount);
                return CompletableFuture.completedFuture("廊桥飞机空调信息历史数据迁移完成！共迁移" + totalCount + "条记录");
            } else {
                log.error("廊桥飞机空调信息历史数据迁移验证失败！MySQL: {}条，ES: {}条", totalCount, esCount);
                return CompletableFuture.completedFuture("廊桥飞机空调信息历史数据迁移验证失败！MySQL: " + totalCount + "条，ES: " + esCount + "条");
            }
        } catch (Exception e) {
            log.error("廊桥飞机空调信息历史数据迁移过程中发生异常", e);
            return CompletableFuture.completedFuture("廊桥飞机空调信息历史数据迁移异常: " + e.getMessage());
        }
    }

    /**
     * 获取飞机空调信息历史数据迁移状态
     */
    public String getAirConditioningInfoHistoryMigrationStatus() {
        try {
            long mysqlCount = bridgeAirConditioningInfoHistoryMapper.countTotal();
            long esCount = bridgeAirConditioningInfoHistoryService.count();
            return String.format("MySQL飞机空调信息历史数据: %d条，ES飞机空调信息历史数据: %d条", mysqlCount, esCount);
        } catch (Exception e) {
            log.error("获取飞机空调信息历史数据迁移状态失败", e);
            return "获取飞机空调信息历史数据迁移状态失败: " + e.getMessage();
        }
    }
}
